package com.shop.wk.config.custom;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
import javax.crypto.SecretKey;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

/**
 * @author 日月星辰
 * @date 2020/12/25 21:32
 * @description
 */
@Component
public class CustomTokenEnhancer implements TokenEnhancer {

	@Override
	public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
		/*
		 * if (accessToken instanceof DefaultOAuth2AccessToken) { DefaultOAuth2AccessToken
		 * token = ((DefaultOAuth2AccessToken) accessToken); //自定义自己的 access_token
		 * token.setValue(customToken()); //自定义生成的 refreshToken token.setRefreshToken(new
		 * DefaultOAuth2RefreshToken(customRefreshToken())); // OAuth2RefreshToken
		 * refreshToken = token.getRefreshToken(); // if (refreshToken instanceof
		 * DefaultOAuth2RefreshToken) { // } // Map<String, Object> additionalInformation
		 * = new HashMap<String, Object>(); // additionalInformation.put("client_id",
		 * authentication.getOAuth2Request().getClientId()); //
		 * token.setAdditionalInformation(additionalInformation); return token; }
		 */
		DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken);

		return result;
	}

	public static void main(String[] args) {
		// 强校验，key至少需要40位以上
		SecretKey key = Keys
				.hmacShaKeyFor("myKeymyKeymyKeymyKeymyKeymyKeymyKeymyKeymyKeymyKey".getBytes(StandardCharsets.UTF_8));
		String jws = Jwts.builder().signWith(key, SignatureAlgorithm.HS256).setIssuer("auth") // 颁发者
				.setSubject("token") // 主题
				.setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000)) // 设置过期时间，1小时后过期，过期解析将会异常
				.setIssuedAt(new Date()) // 设置创建时间
				.setId(UUID.randomUUID().toString()) // just an example id
				.compact();
		System.out.println(jws.length());
		System.out.println(jws);
	}

}
